import os
import traceback
import pyttsx3
from pydub import AudioSegment

# 加载模型
tts = None
# CoquiTts("tts_models/multilingual/multi-dataset/xtts_v2")

# 语音合成类
class TTS:
    engine = None
    rate = 150
    volume = 1.0
    voices = None

    # 初始化
    def __init__(self, driver="pyttsx3", rate=150, volume=1.0, voices=None):
        if driver == "Coqui":
            self.engine = tts
        else:
            self.rate = rate
            self.volume = volume
            self.voices = voices
            self.driver = driver
            self.get_engine()
        
    # 获取驱动
    def get_engine(self):
        self.engine = pyttsx3.init()
        self._set_rate(self.rate)
        self._set_volume(self.volume)
        self._set_voice(self.voices)

    # 设置说话的速度 (可选)
    def _set_rate(self, rate):
        self.engine.getProperty('rate')  # 获取当前速度
        self.engine.setProperty('rate', rate)    # 设置新的速度，默认值为200

    # 设置说话的音调 (可选)
    def _set_voice(self, voices):
        if not voices:
            voices = self.engine.getProperty('voices')
        self.engine.setProperty('voice', voices[0].id)  # 设置为系统默认的声音

    # 设置说话的音量 (可选)
    def _set_volume(self, volume):
        self.engine.getProperty('volume')  # 获取当前音量
        self.engine.setProperty('volume', volume)      # 设置音量范围在0.0到1.0之间

    # 在线播放
    def play_tts(self, text):
        engine = self.get_engine(self.driver)
        try:
            # 将文本转换为语音
            engine.say(text)
            # 等待完成所有的说话命令
            engine.runAndWait()
        except Exception as e:
            print("在线朗读异常：", traceback.print_exc())
            raise Exception(e)
        finally:
            # 停止引擎
            engine.stop()

    # 离线播放
    def play_tts_offline(self, file_path, text, speaker_wav="./spearkers/girl.wav", language="zh-cn"):
        # 判断文件是否存在
        if os.path.exists(file_path):
            return True
        
        # 判断目录是否存在
        dir_path = os.path.dirname(file_path)
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

        try:
            if self.driver == "Coqui":
                return tts.generate_audio(text, file_path, speaker_wav, language)
            else:
                # 将文本转换为语音
                self.engine.save_to_file(text, file_path)
                # 等待完成所有的说话命令
                self.engine.runAndWait()
            
        except Exception as e:
            print("生成离线文件异常", traceback.print_exc())
            return False

        # 检查文件是否存在
        if not os.path.exists(file_path):
            print("离线文件不存在")
            return False

        return True

# 媒体型号工具软件
class MeatFileAction:
    
    # 转换为m3u8
    def tom3u8(self, file_path, output_dir):
        # 创建输出目录
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        # 加载MP3文件
        audio = AudioSegment.from_mp3(file_path)

        # 将MP3文件分割成128秒的片段
        chunks = [audio[i:i + 128000] for i in range(0, len(audio), 128000)]

        # 创建M3U8文件
        m3u8_file = os.path.join(output_dir, "output.m3u8")
        with open(m3u8_file, "w") as f:
            f.write("#EXTM3U\n")
            for i, chunk in enumerate(chunks):
                # 创建片段的MP3文件
                chunk_file = os.path.join(output_dir, f"chunk_{i}.mp3")
                chunk.export(chunk_file, format="mp3")

                # 添加片段到M3U8文件
                f.write(f"#EXTINF:-1, Channel {i}\n")
                f.write(f"{chunk_file}\n")